/**
 * @Author: 陈瑞鹏
 * @Date:   2022-10-21 15:12:26
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2022-10-28 18:54:59
 */
import express from 'express';
import { taskApi } from '../config/api.config';
import reward from '../controllers/reward.controller';
import user from '../controllers/user.contorller';
import { Code } from '../enum/code.enum';
import { FUNC_NAME, PROP_NAME } from '../enum/itemLogs.enum';
import Equip from '../models/equip/equip.model';
import Hero from '../models/hero/hero.model';
import AchTask from '../models/task/achTask.model';
import DailyTask from '../models/task/dailyTask.model';
import Integral from '../models/task/integral.model';
import RandTask from '../models/task/randTask.model';
import Result from '../utils/result';
import utils from '../utils/utils';
const taskRoute = express.Router();
/**
* @api {post} /task/getTaskList 获取任务列表
* @apiGroup 任务
* @apiDescription 
* @apiParam {Number} roleId 角色ID
* @apiName getTaskList
* @apiVersion 1.0.0
*/
taskRoute.post(taskApi.getTaskList, async (req, res) => {
  let { roleId } = req.body;
  let AchTaskRes = await AchTask.find({ roleId });
  let DailyTaskRes = await DailyTask.find({ roleId });
  let retData = {
    AchTaskRes,
    DailyTaskRes
  }
  return res.json({ code: Code.Succ, message: "获取成功!", data: retData });
})

/**
* @api {post} /task/receiveDailyTask 领取每日任务奖励
* @apiGroup 任务
* @apiParam {Number} roleId 角色ID
* @apiParam {Number} id 任务ID
* @apiName receiveDailyTask
* @apiVersion 1.0.0
*/
taskRoute.post(taskApi.receiveDailyTask, async (req, res) => {
  let { roleId, id } = req.body;

  let DailyTaskRes: any = await DailyTask.findOne({ roleId, id });
  if (!DailyTaskRes) throw new Result(Code.Fail, '任务数据错误');

  if (DailyTaskRes.progress < DailyTaskRes.target) {
    throw new Result(Code.Fail, '当前任务未完成');
  }

  if (DailyTaskRes.isReceive) throw new Result(Code.Fail, '当前任务奖励已领取');

  let rewardNum = DailyTaskRes.rewardNum;
  let desc = `任务进度:${DailyTaskRes.progress} 目标:${DailyTaskRes.target}`;

  switch (DailyTaskRes.rewardType) {
    case 1:
      await reward.sendDiamond(roleId, rewardNum, desc, FUNC_NAME.DAILY_TASK);
      break;
    case 2:
      await reward.sendGoldCoin(roleId, rewardNum, desc, FUNC_NAME.DAILY_TASK);
      break;
  }

  await DailyTask.updateOne({ roleId, id }, { isReceive: true });

  let userInfo: any = await user.getUserInfo(roleId);

  DailyTaskRes = await DailyTask.find({ roleId })

  let retData = {
    userInfo,
    DailyTaskRes
  }

  return res.json({ code: Code.Succ, message: "领取成功!", data: retData });
})

/**
* @api {post} /task/upDailyTask 更新每日任务进度
* @apiGroup 任务
* @apiParam {Number} roleId 角色ID
* @apiParam {Number} id 任务ID
* @apiName upDailyTask
* @apiVersion 1.0.0
*/
taskRoute.post(taskApi.upDailyTask, async (req, res) => {
  let { roleId, id, num } = req.body;

  let DailyTaskRes: any = await DailyTask.findOne({ roleId, id });

  if (!DailyTaskRes) throw new Result(Code.Fail, '任务错误');

  let progress = Number(DailyTaskRes.progress) + (Number(num) || 1);

  await DailyTask.updateOne({ roleId, id }, { progress })

  DailyTaskRes = await DailyTask.find({ roleId });

  let retData = {
    DailyTaskRes
  }

  return res.json({ code: Code.Succ, message: "更新成功！", data: retData });
})

/**
* @api {post} /task/receiveAchTask 领取成就任务奖励
* @apiGroup 任务
* @apiParam {Number} roleId 角色ID
* @apiParam {Number} id 任务ID
* @apiParam {Number} target 领取目标
* @apiName receiveAchTask
* @apiVersion 1.0.0
*/
taskRoute.post(taskApi.receiveAchTask, async (req, res) => {
  let { roleId, id, target } = req.body;

  let AchTaskRes: any = await AchTask.findOne({ roleId, id });

  if (!AchTaskRes) throw new Result(Code.Fail, '任务数据错误');

  if (AchTaskRes.progress < target) throw new Result(Code.Fail, '当前成就任务未完成');

  if (AchTaskRes.receivePro.indexOf(target) != -1) throw new Result(Code.Fail, '当前成就任务已领取');

  let AchTaskData: any = await utils.get_id_json(`task/task${id}.json`, target, 'target');

  if (!AchTaskData) throw new Result(Code.Fail, '成就任务数据错误');

  let rewardProp = [{ rewardType: AchTaskData.rewardType0, rewardNum: AchTaskData.rewardNum0 }, { rewardType: AchTaskData.rewardType1, rewardNum: AchTaskData.rewardNum1 }];

  let desc = `[${AchTaskRes.name}] 进度: ${AchTaskRes.progress} 目标: ${target}`;
  for (const iterator of rewardProp) {
    switch (iterator.rewardType) {
      case 1:
        await reward.sendIntegral(roleId, iterator.rewardNum, desc, FUNC_NAME.ACHIEVEMENT_TASK);
        break;
      case 2:
        await reward.sendDiamond(roleId, iterator.rewardNum, desc, FUNC_NAME.ACHIEVEMENT_TASK);
        break;
      case 3:
        await reward.sendGoldCoin(roleId, iterator.rewardNum, desc, FUNC_NAME.ACHIEVEMENT_TASK);
        break;
    }
  }

  AchTaskRes.receivePro.push(target);

  await AchTask.updateOne({ roleId, id }, { receivePro: AchTaskRes.receivePro });
  let userInfo: any = await user.getUserInfo(roleId);
  AchTaskRes = await AchTask.find({ roleId });
  let IntegralRes = await Integral.find({ roleId });

  let retData = {
    userInfo,
    AchTaskRes,
    IntegralRes
  }

  return res.json({ code: Code.Succ, message: "领取成功!", data: retData });
})


/**
* @api {post} /task/upAchTask 更新成就任务进度
* @apiGroup 任务
* @apiParam {Number} roleId 角色ID
* @apiParam {Number} id 任务ID
* @apiParam {Number} progress 需要更新进度数量
* @apiName upAchTask
* @apiVersion 1.0.0
*/
taskRoute.post(taskApi.upAchTask, async (req, res) => {
  let { roleId, id, progress } = req.body;

  let AchTaskRes: any = await AchTask.findOne({ roleId, id });

  if (!AchTaskRes) throw new Result(Code.Fail, '任务错误');

  let proce = Number(AchTaskRes.progress) + Number(progress);

  await AchTask.updateOne({ roleId, id }, { progress: proce });

  AchTaskRes = await AchTask.find({ roleId });

  let retData = {
    AchTaskRes
  }
  return res.json({ code: Code.Succ, message: "更新成功！", data: retData });
})

/**
* @api {post} /task/getIntegralData 获取成就点数数据
* @apiGroup 任务
* @apiParam {Number} roleId 角色ID
* @apiName getIntegralData
* @apiVersion 1.0.0
*/
taskRoute.post(taskApi.getIntegralData, async (req, res) => {
  let { roleId } = req.body;

  let IntegralRes = await Integral.findOne({ roleId });
  let retData = {
    IntegralRes
  }

  return res.json({ code: Code.Succ, message: "获取成功!", data: retData });
})


/**
* @api {post} /task/receiveIntegralReward 领取成就点数奖励
* @apiGroup 任务
* @apiParam {Number} roleId 角色ID
* @apiParam {Number} target 目标
* @apiName receiveIntegralReward
* @apiVersion 1.0.0
*/
taskRoute.post(taskApi.receiveIntegralReward, async (req, res) => {
  let { roleId, target, type } = req.body;

  let IntegralRes: any = await Integral.findOne({ roleId });
  if (!IntegralRes) {
    throw new Result(Code.Fail, '数据错误');
  }

  if (IntegralRes.num < target) {
    throw new Result(Code.Fail, '成就点数不足无法领取');
  }

  let desc = `${target}成就点数奖励`;
  let isTrue = false;
  for (const iterator of IntegralRes.reward) {
    if (iterator.target == target) {
      if (type == 1) {
        if (iterator.isReceive0) {
          throw new Result(Code.Fail, '奖励已领取');
        } else {
          await reward.sendItem(roleId, desc, [{
            type: "diamonds", num: iterator.reward
          }], FUNC_NAME.ACHIEVEMENT_TASK);
          iterator.isReceive0 = true;
          isTrue = true;

        }
      } else if (type == 2) {
        if (iterator.isReceive1) {
          throw new Result(Code.Fail, '奖励已领取');
        } else {
          await reward.sendItem(roleId, desc, [{
            type: "diamonds", num: iterator.reward
          }], FUNC_NAME.ACHIEVEMENT_TASK);
          iterator.isReceive1 = true;
          isTrue = true;
        }
      }
      break;
    }
  }

  if (isTrue) {
    await Integral.updateOne({ roleId }, { reward: IntegralRes.reward });
    let userInfo: any = await user.getUserInfo(roleId);
    IntegralRes = await Integral.findOne({ roleId });
    let retData = {
      userInfo,
      IntegralRes
    }
    return res.json({ code: Code.Succ, message: "领取成功", data: retData });
  } else {
    throw new Result(Code.Fail, '领取失败');
  }
})


/**
* @api {post} /task/upRandTask 更新主线任务进度
* @apiGroup 任务
* @apiParam {Number} roleId 角色ID
* @apiParam {Number} id 任务ID
* @apiParam {Number} progress 需要更新进度数量
* @apiName upRandTask
* @apiVersion 1.0.0
*/
taskRoute.post(taskApi.upRandTask, async (req, res) => {
  let { roleId, id, progress } = req.body;

  let userInfo: any = await user.getUserInfo(roleId);

  let RandTaskRes: any = await RandTask.findOne({ roleId, id });

  if (!RandTaskRes) throw new Result(Code.Fail, '任务错误');

  if (RandTaskRes.target <= RandTaskRes.progress) throw new Result(Code.Fail, '该任务已完成');

  if (id > 101) {
    let taskRes: any = await RandTask.findOne({ roleId, id: id - 1 });
    if (taskRes.target > taskRes.progress) throw new Result(Code.Fail, '前置任务未完成');
  }

  let proce = Number(RandTaskRes.progress) + Number(progress);

  await RandTask.updateOne({ roleId, id }, { progress: proce });

  userInfo = await user.getUserInfo(roleId);

  RandTaskRes = await RandTask.find({ roleId });

  let retData = {
    userInfo,
    RandTaskRes
  }

  return res.json({ code: Code.Succ, message: "更新成功!", data: retData });

})

/**
* @api {post} /task/receiveMainTask 领取主线任务奖励
* @apiGroup 任务
* @apiParam {Number} roleId 角色ID
* @apiParam {Number} id 任务ID
* @apiName receiveMainTask
* @apiVersion 1.0.0
*/
taskRoute.post(taskApi.receiveRandTask, async (req, res) => {
  let { roleId, id } = req.body;

  let RandTaskRes: any = await RandTask.findOne({ roleId, id });
  if (!RandTaskRes) throw new Result(Code.Fail, '任务数据错误');

  if (RandTaskRes.isReceive) throw new Result(Code.Fail, '当前任务奖励已领取');

  if (RandTaskRes.progress < RandTaskRes.target) throw new Result(Code.Fail, '任务未完成无法领取奖励');

  let RandTaskData: any = await utils.get_id_json('task/randTask.json', id, 'id');

  let desc = `${RandTaskData.describe} 进度:${RandTaskRes.progress} 目标:${RandTaskRes.target}`;
  let rewardNum = RandTaskData.reward
  switch (RandTaskData.rewardType) {
    case 1:
      await reward.sendGoldCoin(roleId, rewardNum, desc, FUNC_NAME.RAND_TASK);
      break;
    case 2:
      await reward.sendDiamond(roleId, rewardNum, desc, FUNC_NAME.RAND_TASK);
      break;
    case 3:
      await reward.sendHero(roleId, rewardNum, desc, FUNC_NAME.RAND_TASK);
      break;
    case 4:
      await reward.sendEquip(roleId, rewardNum, desc, FUNC_NAME.RAND_TASK);
      break;
    case 5:
      break;

  }
  let nextTaskRes = await RandTask.findOne({ roleId, id: Number(id) + 1 });
  
  if (nextTaskRes) {
    await RandTask.updateOne({ roleId, id }, { isReceive: true });
  } else {
    //重新开始循环
    await RandTask.updateMany({ roleId }, { isReceive: false, progress: 0 });
  }

  let userInfo: any = await user.getUserInfo(roleId);
  let HeroRes = await Hero.find({ roleId });
  let EquipRes = await Equip.find({ roleId });
  RandTaskRes = await RandTask.find({ roleId });

  let retData = {
    userInfo,
    HeroRes,
    EquipRes,
    RandTaskRes
  }

  return res.json({ code: Code.Succ, message: "领取成功!", data: retData });
})

export default taskRoute;

